package com.halflife.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

public class NioSocketServer {
    public static void main(String[] args) throws IOException,InterruptedException {
        LinkedList<SocketChannel> clients = new LinkedList<>();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(9090));
        serverSocketChannel.configureBlocking(false);

        while (true) {
            Thread.sleep(100l);
            SocketChannel client = serverSocketChannel.accept();
            System.out.println(client);
            if (client != null) {
                client.configureBlocking(false);
                clients.add(client);
            }

            ByteBuffer byteBuffer = ByteBuffer.allocate(8096);

            byteBuffer.clear();
            for (SocketChannel sc : clients) {
                int limit = sc.read(byteBuffer);
                if (limit > 0) {
                    byteBuffer.flip();
                    byte[] bytes = new byte[byteBuffer.limit()];
                    byteBuffer.get(bytes);
                    System.out.println(new String(bytes));
                    byteBuffer.clear();
                    byteBuffer.put(bytes);
                    byteBuffer.flip();
                    sc.write(byteBuffer);
                }
                byteBuffer.clear();
            }
        }
    }
}
